package impl

import (
	"fmt"
	model2 "gf-xb-api/cwt/filter/model"
	"gf-xb-api/utility/xstr"
	"strings"

	"github.com/gogf/gf/v2/database/gdb"
)

type StartsWithOrReverseStartsWith[T any] struct {
	Op        string
	FieldName string
	Rule      *model2.FilterRule[T]
}

func (p *StartsWithOrReverseStartsWith[T]) Parse(op string, fieldName string, rule *model2.FilterRule[T], m *gdb.Model) *gdb.WhereBuilder {

	// 判断fieldName是否带着point, 如果带着，则将point后面的字段加上Reverse
	var reverseField string
	pos := strings.Index(fieldName, ".")

	if pos == -1 {
		reverseField = "Reverse" + fieldName // 固定格式 Reverse+field
	} else {
		reverseField = fieldName[:pos+1] + "Reverse" + fieldName[pos+1:]
	}

	val := rule.Value
	reverseVal := xstr.Reverse(val)

	val = fmt.Sprintf("%s%%", val)
	reverseVal = fmt.Sprintf("%s%%", reverseVal)

	if op == model2.AndOperator {
		return m.Builder().WhereLike(fieldName, val).WhereOrLike(reverseField, reverseVal)
	}

	return m.Builder().WhereOr(m.WhereLike(fieldName, val).WhereOrLike(reverseField, reverseVal))
}
